package com.liuww.mvc.utils;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import com.liuww.mvc.bean.XmlBean;

public class StrutsXmlPrase {

	public static Map<String, XmlBean> praseStrutsXml(String filepath) {
		Map<String, XmlBean> xmlMap = new HashMap<String, XmlBean>();
		File strutsXml = new File(filepath);
		SAXBuilder builder = new SAXBuilder();
		try {
			Document document = builder.build(strutsXml);
			Element root = document.getRootElement();
			Element formbeans = root.getChild("form-beans");
			List<Element> formbean = formbeans.getChildren();
			Map<String, String> beanMap = new HashMap<String, String>();
			for (Element bean : formbean) {
				String name = bean.getAttributeValue("name");
				String type = bean.getAttributeValue("type");
				beanMap.put(name, type);
			}
			Element actionRoot = root.getChild("action-mapping");
			List<Element> actionList = actionRoot.getChildren();
			for (Element action : actionList) {
				String name = action.getAttributeValue("name");
				String type = action.getAttributeValue("type");
				String path = action.getAttributeValue("path");
				String beanType = beanMap.get(name);
				XmlBean xmlBean = new XmlBean();
				xmlBean.setName(name);
				xmlBean.setFormBean(beanType);
				xmlBean.setAction(type);
				xmlBean.setPath(path);
				Map<String, String> forwardMap = new HashMap<String, String>();
				List<Element> forwardList = action.getChildren();
				for (Element forward : forwardList) {
					String forwardname = forward.getAttributeValue("name");
					String forwardpath = forward.getAttributeValue("path");
					forwardMap.put(forwardname, forwardpath);
				}
				xmlBean.setForward(forwardMap);
				xmlMap.put(path, xmlBean);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return xmlMap;
	}
}
